package com.orhon.smartcampus.modules.systemctl.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.OrgDutiesDao;
import com.orhon.smartcampus.modules.systemctl.entity.OrgDuties;
import com.orhon.smartcampus.modules.systemctl.gqlInputModel.GQLDutyInput;
import com.orhon.smartcampus.modules.systemctl.inputMapper.DutyInputMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddDutyMutation implements DataFetcher {



    @Autowired
    OrgDutiesDao orgDutiesDao;

    /**
     * 新增/修改职务的维护
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {
        GQLDutyInput input = DutyInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        OrgDuties orgDuties = null;

        if (input.getId() != null) {
            orgDuties = orgDutiesDao.get(OrgDuties.class, input.getId());
            orgDuties.setUpdatedAt(new Date());
        } else {
            orgDuties = new OrgDuties();
            orgDuties.setCreatedAt(new Date());
        }
        if(input.getDuties_name() != null){

            orgDuties.setDutiesName(JSON.toJSONString(input.getDuties_name()));
        }
        if(input.getDuties_order() != null){

            orgDuties.setDutiesOrder(input.getDuties_order());
        }
        if(input.getParent_id() != null) {
            orgDuties.setSystemctlOrgDutiesByParentId(orgDutiesDao.get(OrgDuties.class, input.getParent_id()));
        }
        if(input.getLevel() != null){

            orgDuties.setLevel(input.getLevel());
        }
        try{
            orgDutiesDao.saveOrUpdate(orgDuties);
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }
}

